/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SecureUtil;

import java.net.InetAddress;
import java.util.Date;
import java.util.Hashtable;

/**
 *
 * @author Gwang
 */
public class CookieHelper {

    public Hashtable cookiecounter = new Hashtable();
    private final int falsetrial = 3;
    private final int suspecious = 200;
    public CookieHelper() {
        cookiecounter = new Hashtable();
    }
    // return false : run out of all quota
    public boolean decreaseCookieQuota(String cookie) {
        if (cookiecounter.containsKey(cookie)) {
            Integer i = (Integer) cookiecounter.get(cookie);
            if(i<0) cookiecounter.put(cookie, i-1);
            if (i <= -1*falsetrial) {
                return false;
            }
        } else {
            cookiecounter.put(cookie, -1);
        }
        return true;
    }
    public boolean hasLogedinRecent(String cookie){
        return ((Integer)cookiecounter.get(cookie) == 0);
    }
    public void ResetCookieState(String cookie){
            cookiecounter.put(cookie, 0);
    }
    public boolean IncreaseCookie(String cookie){
        if (cookiecounter.containsKey(cookie)) {
            Integer i = (Integer) cookiecounter.get(cookie);
            if(i>=0) i++;
            if (i>suspecious) return false;
        } else {
            return false;
        }
        return true;
    }
    public void clearCookieCounter() throws Exception {
        cookiecounter.clear();
    }
    public static String getCookie(InetAddress ip, int port, int rand) throws Exception {
        Long milsec = new Date().getTime();
        Long hour = milsec / 3600000L;
        Packer packer = new Packer();
        packer.addElement(Packer.DataType.INTEGER, rand);
        packer.addElement(Packer.DataType.BYTES, ip.getAddress());
        //packer.addElement(Packer.DataType.INTEGER, port);
        packer.addElement(Packer.DataType.LONG, hour);
        return HashHelper.SHA1String(packer.pack());
    }

    public static boolean verifyCookie(InetAddress ip, int port, int rand, String cookie)
            throws Exception {
        return cookie.equals(getCookie(ip, port, rand));
    }
}
